<template>
  <div class="login-body">
    <image></image>
    <button class="auth-login" @click="getLoginChange" :disabled="loginLoading">
      授权登录
    </button>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, getCurrentInstance } from "vue";
import { getLoginAuth } from "@/api/common";
import { Result, ResultError } from "@/types";
import { useUser } from "@/store";
const userStore = useUser();
const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const loginLoading = ref<boolean>(false);

const loginData = ref<{
  encryptedData: string;
  iv: string;
  signature: string;
  code: string;
}>({
  encryptedData: "",
  iv: "",
  signature: "",
  code: "",
});

const getLoginChange = () => {
  if (loginLoading.value) {
    return;
  }
  loginLoading.value = true;
  uni.showLoading({
    title: "正在登录...",
  });
  uni.getUserProfile({
    desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      loginData.value.encryptedData = res.encryptedData;
      loginData.value.iv = res.iv;
      loginData.value.signature = res.signature;
      uni.login({
        success(loginRes) {
          loginData.value.code = loginRes.code;
          toLogin();
        },
      });
    },
    fail(err) {
      uni.hideLoading;
      $utils.errorMsg(err.errMsg);
    },
  });
};

const toLogin = () => {
  getLoginAuth(loginData.value)
    .then((res: Result) => {
      userStore.setToken(res.data.token);
      userStore.setUser(res.data.user);
      $utils.successMsg(res.message);
      toBack();
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
  loginLoading.value = false;
  uni.hideLoading();
};

const toBack = () => {
  setTimeout(() => {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    if (prevPage) {
      uni.navigateBack({
        delta: 1,
      });
    } else {
      $utils.routeRedirectTo("/pages/user/index");
    }
  }, 1500);
};

onMounted(() => {});
</script>


<style scoped>
.login-body {
  width: 80%;
  height: 400rpx;
  position: fixed;
  top: calc(50% - 200px);
  left: 10%;
}
.auth-login {
  height: 80rpx;
  line-height: 80rpx;
  border-radius: var(--base-radius);
  color: #fff;
  text-align: center;
  border: 1px solid;
  width: 100%;
  margin: 0;
  background: var(--base-default);
  font-size: var(--base-size);
  border: none !important;
}
</style>